import React, { Component } from 'react'

class Todolist extends Component {

  state = {
      val:"",
      arr:[
          {
            action:"吃饭",
            flag:false
          },
          {
            action:"睡觉",
            flag:false
          },
          {
            action:"学习",
            flag:false
          },
      ]
  }
  checkval(e){
    console.log(e.target.value)
    this.setState({
        val:e.target.value
    })
  }
  add(){
     console.log(this.state.val)
     let obj = {
         flag:false
     }
     obj.action = this.state.val
     console.log(obj,11111);
     this.state.arr.push(obj)
     this.setState({
         arr:this.state.arr
     })
     setTimeout(()=>{
        this.setState({
            val:""
        })
     },100)

  }
  checkflag(ind){
     this.state.arr.forEach((item,index)=>{
         if (index == ind) {
             item.flag = !item.flag
         }
     })
     this.setState({
         arr:this.state.arr
     })
  }
  render() {
    let {arr,val} = this.state
    return (
      <div>
          <p>
              <input type="text" value={val} onChange={this.checkval.bind(this)} />
              <button onClick={this.add.bind(this)}>add</button>
          </p>
           {
               arr&&arr.length?arr.map((item,index)=>{
                //    循环的时候key只要是唯一且不一样得就行，不一定非是index
                   return <li key={index}>
                       <input type="checkbox" checked={item.flag} onChange={this.checkflag.bind(this,index)}/>
                       <span>{item.action}</span>
                        {
                            item.flag?<button>已完成</button>:<button>"未完成"</button>
                        }
                      
                       <span>x</span>
                   </li>
               }):"请添加一条数据"
           }
      </div>
    )
  }
}

export default Todolist